<?php
/**
 * 
 * 根据话题抓取微博数据
 * @author yangchao
 * @since 2012-03-19
 */
if (!file_exists("../SINASRV_CONFIG")) {
	echo "Read the sinasrv config error!\n";
//	exit();
} else {
   $array_config = parse_ini_file("../SINASRV_CONFIG", true); var_dump($array_config);
   
   $_SERVER = array_merge($_SERVER, $array_config); 
}

$search_array = array("求大神","求教我玩","求开黑","求组队","求好友","求给力","求队友","求大腿","求师傅","求战友");
/*ini_set("display_errors",ture);
error_reporting(E_ALL);*/

define("CRON_NAME","qq_want_");//cro名称，要求唯一
set_time_limit(0);
$_GET["db_debug"] = true;
$_GET["no_pref_debug"] = true;
   //$_GET["api_debug"] = true;
echo "<pre>";

//15分钟一次,执行1000条
define("PCOUNT",10);//每次处理多少mid
define("MAX_PAGE",1000); //定义每个进程处理最大的页数
define("TOTAL_PROCESS",1);//添加新进程需要更新这个配置
define("NOW_PROCESS",$argv[1] ? $argv[1] : 0);//当前进程ID=0 可以申请如下php xxx 1
define("CRON_START_TIME",time());



include_once($_SERVER['DOCUMENT_ROOT'] ."/include/user/inc.php");
include_once($_SERVER['DOCUMENT_ROOT'] ."/include/tucao/inc.php");
include_once($_SERVER['DOCUMENT_ROOT'] ."/include/mblog/inc.php");
include_once($_SERVER['DOCUMENT_ROOT'] ."/include/qq/inc.php");
include_once($_SERVER['DOCUMENT_ROOT'] ."/mblog/inc.php");
class mod_cron_engine_main extends mod_cron_engine
{
	function __construct($current_process_id)
	{
		parent::__construct($current_process_id,CRON_NAME);
	}
	
	
	function craw()
	{
		$this->get_data();
	}
	
	
	function  run()
	{
		//开始跑cron之前预先获取数据（start_id等）
		$this->before_run();
		
		//正式获取数据
		$this->craw();
		
		
		$this->after_run();
	}
	
	
	function get_data()
	{
		global $config,$search_array;
		
		$mblog_from_api = new mblog_from_api();
		$db_cron_get_manage = new db_cron_get_manage();
		foreach($config["site_name"] as $site_id => $site_name)
		{
			$black_word = $config["site_black_word"][$site_id]; 
			if(!$site_id)continue;
			foreach($search_array as $key2 => $value2)
			{
				$topic_new = $site_name." ".$value2;
				$get_key = CRON_NAME.$topic_new;
				$get_res = $db_cron_get_manage->cron_get_item_by_key($get_key);
				$cron_start_time  = $get_res["get_num"];
				$this->get_list_by_topic($topic_new,$site_id,1,$cron_start_time,$show_type,$black_word,$site_name,$site_name,$get_key);
				
			}
			
			//如果有别名
			$topic_alias = $config["site_alias"][$site_id] ;
			if($topic_alias)
			{
				foreach($topic_alias as $topic_alias_item)
				{
					foreach($search_array as $key2 => $value2)
					{
						$topic_new = $topic_alias_item." ".$value2;
						$get_key = CRON_NAME.$topic_new;
						$get_res = $db_cron_get_manage->cron_get_item_by_key($get_key);
						$cron_start_time  = $get_res["get_num"];
						$this->get_list_by_topic($topic_new,$site_id,1,$cron_start_time,$show_type,$black_word,$site_name,$topic_alias_item,$get_key);
						
					}
				}
				
			}
			
		}
		
		
		//做完这个操作后，更新求组队用户的在线状态
		//$this->update_user_online();
		
		
		
	}	
	
	//根据话题抓取数据并入库
	function get_list_by_topic($topic,$id,$p=1,$starttime="",$show_type="",$black_word="",$topic_real="",$topic_alias="",$get_key="")
	{
		global $config;
		
		$db_base = new db_base();
		$mblog_from_api = new mblog_from_api();
		$db_user_info = new db_user_info();
		$db_mblog_want_content = new db_mblog_want_content();
		$mblog_get_mblog_from_qq = new mblog_get_mblog_from_qq();
		echo "start_toppic:{$topic}\n<br>";
		
		//执行时间超过60分钟，退出
		if(time() - CRON_START_TIME > 3600)
		{
			exit;
		}
		
		if($topic)
		{
			echo "starttime:{$starttime}\n<br>";
			
			
			//根据话题抓取
			$mblog_list = $mblog_get_mblog_from_qq->get_mblog_list_by_search($topic,$pcount,$p,"0","1","",$starttime,$end_time);
			
			
			echo "{$topic}:count:{$mblog_list["data"]["count"]}|get_count".count($mblog_list["data"]["result"]).":p:{$p}<br>\n";	
			
			if($mblog_list["data"]["result"])
			{
				foreach($mblog_list["data"]["result"] as $value1)
				{
					$value1["text"] = $value1["origtext"];
					$u_time = $value1["timestamp"];
					if($max_time < $u_time) $max_time = $u_time;
						
					echo "time_compare:".$u_time." == {$starttime}<br>\n";
					
					if($u_time == $starttime)
					{
						continue;
					}
					
					
					
					//@$db_user_info->cron_insert_user_info($uid,$sex,$user_nickname,$province,$city,$company,$school,$verified_type,$bithday,$desc);
					
					
					$db_user_search = new db_user_search();
					$from_type=$config["user_from_type"]["want"];
					$user_info = new user_info();
					$qq_user_info = $user_info->get_user_info_by_openid($value1["openid"]);
					
					/*
						 * $last_insert_search_id = $db_user_search->insert_user_search($uid,$sex,$province ,$city,$location,$birthday,$id,0,$user_nickname,$verified_type,$from_type);
				
					 * $this->get_mblog_by_uid($uid,$id,$topic,$show_type);
					
					continue;*/
					
					
					$check_source = preg_replace("/<.*?>/","",$value1["source"]);
					
					echo $check_source."\n";
					$check_res = true;
					/*foreach($config["check_mblog_cron_source"] as $value)
					{
						if(stripos($check_source,$value) !== false)
						{
							
							$check_res = true;
							break;
						}
					}
					*/
					/*$black_word = unserialize($black_word);*/
					//检查黑名单的方法
					if($black_word)
					{
						$checked = true;
						foreach($black_word as $value) 
						{
							if(stripos($value1["text"],$value) !== false)
							{
								$checked = false;
								break;
							}
						}
						if($checked == false)
						{
							continue;
						}
					}
					
					if($check_res == true)
					{
						
						
						$create_time = date("Y-m-d H:i:s",$u_time);
						
						
						//获取微博坐标信息
						/*$coordinates = "";
						if($value1["geo"]["coordinates"])
						{
							$coordinates = $value1["geo"]["coordinates"][1].",".$value1["geo"]["coordinates"][0];
						}
						//获取坐标对应地址
						if($coordinates)
						{
							 $address_info = $mblog_from_api->api_geo_to_address($coordinates);
							if($address_info["data"]["result"])
							{
								$location = $address_info["data"]["result"][0]["province_name"]." ".$address_info["data"]["result"][0]["city_name"]." ".$address_info["data"]["result"][0]["address"];
							} 
						}
						*/
					
						/*if($value1["bmiddle_pic"])
						{
							$res = get_image::get_image_size_by_url($value1["bmiddle_pic"]);
						
							$srcW = $res["width"]; 
							$srcH = $res["height"]; 
							
							echo "image:{$value1["bmiddle_pic"]} $srcW - $srcH \n";
							
							$pic_width_pubu = PUBU_WIDTH;
							$pic_height_pubu = intval($srcH/($srcW/$pic_width_pubu));
						
						}
						else
						{
							$pic_width_pubu= 0;
							$pic_height_pubu = 0;	
						}*/
						
						$value1["text"] = mysql_escape_string($value1["text"]);
						$date =  date("Y-m-d",strtotime($value1["created_at"]));
						$mid = $value1["id"] ;
						
						$reposts_count = $value1["reposts_count"] ;
						
						if($value1["image"][0])
						{
							$pic_url = $value1["image"][0]."/460";
						}
						else
						{
							$pic_url = "";
						}
						$verified_type = $value1["is_vip"];
						$sex = $qq_user_info["sex"];
						$from = 1;
						$head_url = $qq_user_info["head_url"];
					
						$last_insert_id = $db_mblog_want_content->cron_insert_mblog_want_content($value1["text"],$id,$topic,$topic_real,$pic_url,$pic_width_pubu,$pic_height_pubu,$value1["from"],$show_type,$from,$qq_user_info["uid"],$qq_user_info["user_nickname"],$date,$mid,$create_time,$reposts_count,
						$sex,$verified_type,$value1["mblog_id"],$head_url);
						/*if($last_insert_id)
						{
							$res = $this->comment_to_this($value1["user"]["id"],$u_time,$id,$topic_real,$mid,$value1["user"]["screen_name"],$sex);
							
						}*/
					
					}
				}
		
			}
				
		}
		
		
		if($p == 1)//当为第一页时，检查是否有多页需要抓取
		{	//最大页数为20，接口限制
			$total_page = ceil($mblog_list["data"]["count"]/50);
			$total_page = $total_page > 20 ? 20 : $total_page;
			echo "topic_page_count:{$total_page}<br>\n";
			
			if($max_time && $max_time > $starttime)
			{
				
				$db_cron_get_manage = new db_cron_get_manage();
				$get_res = $db_cron_get_manage->cron_replace_into_data($get_key,$max_time);
			}
				
			for($i = 2 ; $i <= $total_page;$i++)
			{
				$this->get_list_by_topic($topic,$id,$i,$starttime,$show_type,$black_word,$topic_real,$topic_alias,$get_key);
			}
			
		
			
			
		}
			
	}
	
	
	
	function update_user_online()
	{
		$hour = date("H");
		if($hour > 1 && $hour < 7)
		{
			continue;
		}
		$db_base = new db_base();
		$sql = "update mblog_want_content set online_status = 0 ";
		$db_base->query($sql);
		$sql ="select distinct(create_uid) as create_uid from mblog_want_content order by create_time desc limit 5000 ";
		
		$user_list = $db_base->select($sql);
		
		$uid_array = array();
		foreach($user_list as $value)
		{
			$uid_array[] = $value["create_uid"];
		}
		
		
		$mblog_from_api = new mblog_from_api();
		
		foreach($uid_array as $key => $uids)
		{
			
			$user_mblog_list = $mblog_from_api->api_get_user_info_by_uids($uids,"",1,"",true);

			foreach($user_mblog_list["data"]["result"] as $key2 => $value2)
			{
				if($value2["online_status"] == 1)
				{
					$sql = "update mblog_want_content set update_date=unix_timestamp(create_time)+86400,online_status=1 where create_uid = {$value2["id"]} ";
					$db_base->query($sql);
				}
				else
				{
				/*	$sql = "update mblog_want_content set update_date=unix_timestamp(create_time),online_status=0 where create_uid = {$value2["id"]} ";
					$db_base->query($sql);*/
				}
				
			}
			
		}
		
	}
	
	
	
	function comment_to_this($uid,$time,$topic_id,$topic,$mid,$nick,$sex)
	{
		global $last_content;
		
		return false;
		
		$now = time();
		
		if(( $now - $time) >10000)//3个小时前的不处理
		{
			return false;
		}
		if(!$mid)
		{
			return false;
		}
		
		//取上几条求组的信息
		$db_mblog_want_content = new db_mblog_want_content();
		$db_base = new db_base();
		if($sex == "m")
		{
			$sex= 1;
			$sex_get = 0;//如果是男的推荐女的信息
		}
		else
		{
			$sex= 0;
			$sex_get = 1;
		}
		/*$mblog_from_api = new mblog_from_api();
		$list = $db_mblog_want_content->cron_get_info_by_tipoc_id($topic_id,$sex_get);
		$user_nicks = array();
		$uid_array = array();
		foreach($list as $value)
		{
			$uid_array[] = $value["create_uid"];
		}
		
		
		$user_mblog_info = $mblog_from_api->api_get_user_info_by_uids(join(",",$uid_array),"","",1);
		$user_mblog_array=array();
		$online_user = 0;
		$online_nick = array();
		$no_online_nick = array();
		foreach($user_mblog_info["data"]["result"] as $key => $value)
		{
			$user_mblog_array[$value["id"]] = $value;
			if($value["online_status"] == 1)
			{
				$online_nick[] = "@{$value["name"]}";
				$online_user++;
			}
			else
			{
				$no_online_nick[] = "@{$value["name"]}";
			}
		}
		
		
		if($online_user < 3 )
		{
			$not_get_all = true;
			$list1 = $db_mblog_want_content->cron_get_info_by_tipoc_id($topic_id,$sex);
			$uid_array1 = array();
			foreach($list1 as $value)
			{
				$uid_array1[] = $value["create_uid"];
			}
			$user_mblog_info1 = $mblog_from_api->api_get_user_info_by_uids(join(",",$uid_array1),"","",1);
			$user_mblog_array1=array();
			foreach($user_mblog_info1["data"]["result"] as $key => $value)
			{
				$user_mblog_array1[$value["id"]] = $value;
				if($value["online_status"] == 1)
				{
					$online_nick[] = "@{$value["name"]}";
					$online_user++;
				}
				else 
				{
					$no_online_nick[] = "@{$value["name"]}";
				}
			}
		}
		
		$online_nick = array_unique($online_nick);
		$online_nick = array_slice($online_nick,0,3);
		
		if(count($online_nick) < 3)
		{
			$not_all_online = true;
			$online_nick =  array_merge($online_nick,$no_online_nick);
			$online_nick = array_unique($online_nick);
			$online_nick = array_slice($online_nick,0,3);
		}
		
		
		if(!$online_nick)
		{
			return false;
		}
		$user_nicks = join(" ",$online_nick);
		
		
		if($not_get_all)
		{
			if($not_all_online)
			{
				$content= "亲，我发现你正在找一起玩{$topic}的人，给你推荐几个也在找的人 $user_nicks ,这是他们的昵称，如果想了解更多想一起玩游戏的人：http://yxxiu.com/want/";

			
			}
			else
			{
				$content= "亲，我发现你正在找一起玩{$topic}的人，给你推荐几个也在找的人 $user_nicks ,这是他们的昵称，现在都还在线，抓紧联系他们吧。如果想了解更多想一起玩游戏的人：http://yxxiu.com/want/";
			
			}
			
		}
		else 
		{
			if($sex == 1 )
			{
				if($not_all_online)
				{
					$content= "小哥，我发现你正在找一起玩{$topic}的人，给你推荐几个也在找人一起玩的妹子 $user_nicks ,这是他们的昵称，如果你是高手的话就带带吧。了解更多想一起玩游戏的妹子：http://yxxiu.com/want/?sex=0 ";
				
				}
				else
				{
					$content= "小哥，我发现你正在找一起玩{$topic}的人，给你推荐几个也在找人一起玩的妹子 $user_nicks ,这是他们的昵称，抓紧时间，妹子们都还在线。了解更多想一起玩游戏的妹子：http://yxxiu.com/want/?sex=0 ";
				
				}
				
			}
			else
			{
				if($not_all_online)
				{
					$content= "美女，我发现你正在找一起玩{$topic}的人，给你推荐几个也在找人一起玩的帅哥 $user_nicks ,运气好的话可能是高手哈。不用回复我哈。了解更多想一起玩游戏的人：http://yxxiu.com/want/ ";
			
				}
				else
				{
					$content= "美女，我发现你正在找一起玩{$topic}的人，给你推荐几个也在找人一起玩的帅哥 $user_nicks ,他们现在还在线，抓紧时间去问问吧，不用回复我哈。。了解更多想一起玩游戏的人：http://yxxiu.com/want/ ";
			
				}
				
				$content .=" 插个广告 :QQ群（277584921），游戏玩家群，希望大家能进来交流！";
			}
			
		}
			*/
		
		
		$content = "亲，我发现你正在找一起玩{$topic}的人,这里 http://yxxiu.com/want/?topic_id={$topic_id} 有很多跟你一样兴趣的人，可以直接私信他们哦。。";
		
		$admin_uid = 1743803187;
		
		$db_user_token = new db_user_token();
		$token_info  = $db_user_token->get_token_by_uid_and_appkey($admin_uid,WB_AKEY);
		$token = $token_info["access_token"];
		$SaeTClientV2 = new SaeTClientV2( WB_AKEY , WB_SKEY , $token);
		$res = $SaeTClientV2->send_comment( $mid, $content );
		var_dump($res);
		$cid = $res["id"];
		if($cid)
		{
			
			sleep(5);
			
		}
		//调用太频繁就退出
		if($res["error_code"] == 10024 || $res["error_code"] == 20016  )
		{
			$admin_uid = 2632497997;
			$db_user_token = new db_user_token();
			$token_info  = $db_user_token->get_token_by_uid_and_appkey($admin_uid,WB_AKEY);
			$token = $token_info["access_token"];
			$SaeTClientV2 = new SaeTClientV2( WB_AKEY , WB_SKEY , $token);
			$res = $SaeTClientV2->send_comment( $mid, $content );
			sleep(15);
			
			//exit;
		}
		
		return true;
	
	}
	
}

$m = new mod_cron_engine_main(NOW_PROCESS);
$m->run();
